<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { useProductStore } from '@/stores/product'

const productStore = useProductStore()

// 筛选条件
const filters = reactive({
  search: '',
  category: '',
  brand: '',
  status: '', // on/off
})

// 列表与分页
const pageSize = ref(10)
const currentPage = ref(1)
const selectedIds = ref(new Set())

const filteredList = computed(() => productStore.getFilteredProducts(filters))
const total = computed(() => filteredList.value.length)
const totalPages = computed(() => Math.max(1, Math.ceil(total.value / pageSize.value)))
const pageList = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value
  return filteredList.value.slice(start, start + pageSize.value)
})

// 全选控制
const isAllChecked = computed(() => pageList.value.length > 0 && pageList.value.every(item => selectedIds.value.has(item.id)))
const toggleCheckAll = (checked) => {
  pageList.value.forEach(item => {
    if (checked) selectedIds.value.add(item.id)
    else selectedIds.value.delete(item.id)
  })
}

const toggleRowChecked = (id, checked) => {
  if (checked) selectedIds.value.add(id)
  else selectedIds.value.delete(id)
}

// 统计
const totalOn = computed(() => productStore.totalOnSale)
const totalOff = computed(() => productStore.totalOffSale)

// 表单弹窗
const visible = ref(false)
const isEdit = ref(false)
const editId = ref('')
const form = reactive({
  code: '',
  name: '',
  category: '',
  brand: '',
  specification: '',
  unit: '件',
  salePrice: 0,
  costPrice: 0,
  status: 'off',
  barcode: '',
})

const resetForm = () => {
  editId.value = ''
  isEdit.value = false
  Object.assign(form, {
    code: '', name: '', category: '', brand: '', specification: '', unit: '件',
    salePrice: 0, costPrice: 0, status: 'off', barcode: ''
  })
}

const openAdd = () => { resetForm(); visible.value = true }
const openEdit = (row) => {
  resetForm()
  isEdit.value = true
  editId.value = row.id
  Object.assign(form, {
    code: row.code,
    name: row.name,
    category: row.category,
    brand: row.brand,
    specification: row.specification,
    unit: row.unit,
    salePrice: row.salePrice,
    costPrice: row.costPrice,
    status: row.status,
    barcode: row.barcode,
  })
  visible.value = true
}

const validate = () => {
  if (!form.code || !form.name) return '请填写编码与名称'
  if (Number(form.salePrice) < 0 || Number(form.costPrice) < 0) return '价格不能为负数'
  return ''
}

const submitForm = () => {
  const msg = validate()
  if (msg) { alert(msg); return }
  if (isEdit.value) {
    productStore.updateProduct(editId.value, { ...form })
  } else {
    productStore.addProduct({ ...form })
  }
  visible.value = false
}

const removeRow = (row) => {
  if (confirm(`确认删除商品【${row.name}】?`)) {
    productStore.deleteProduct(row.id)
    selectedIds.value.delete(row.id)
  }
}

const toggleStatus = (row) => {
  productStore.toggleStatus(row.id)
}

const batchOn = () => {
  if (selectedIds.value.size === 0) { alert('请选择商品'); return }
  productStore.batchToggleStatus(Array.from(selectedIds.value), 'on')
}

const batchOff = () => {
  if (selectedIds.value.size === 0) { alert('请选择商品'); return }
  productStore.batchToggleStatus(Array.from(selectedIds.value), 'off')
}

const exportData = () => {
  productStore.exportProducts(filteredList.value)
}

const resetFilters = () => {
  filters.search = ''
  filters.category = ''
  filters.brand = ''
  filters.status = ''
  currentPage.value = 1
}

onMounted(() => {
  if (productStore.productList.length === 0) {
    productStore.initializeProducts()
  }
})
</script>

<template>
  <div class="product-page">
    <div class="header">
      <div class="title">商品管理</div>
      <div class="actions">
        <button class="primary" @click="openAdd">新增商品</button>
        <button @click="batchOn">批量上架</button>
        <button @click="batchOff">批量下架</button>
        <button @click="exportData">导出</button>
      </div>
    </div>

    <div class="stats">
      <div class="card">
        <div class="num">{{ total }}</div>
        <div class="label">商品总数</div>
      </div>
      <div class="card on">
        <div class="num">{{ totalOn }}</div>
        <div class="label">上架</div>
      </div>
      <div class="card off">
        <div class="num">{{ totalOff }}</div>
        <div class="label">下架</div>
      </div>
    </div>

    <div class="filters">
      <input v-model="filters.search" class="input" placeholder="搜索 名称/编码/条码" />
      <select v-model="filters.category" class="select">
        <option value="">全部类别</option>
        <option v-for="c in productStore.categories" :key="c" :value="c">{{ c }}</option>
      </select>
      <select v-model="filters.brand" class="select">
        <option value="">全部品牌</option>
        <option v-for="b in productStore.brands" :key="b" :value="b">{{ b }}</option>
      </select>
      <select v-model="filters.status" class="select">
        <option value="">全部状态</option>
        <option value="on">上架</option>
        <option value="off">下架</option>
      </select>
      <button class="ghost" @click="resetFilters">重置</button>
    </div>

    <div class="table-wrap">
      <table class="table">
        <thead>
          <tr>
            <th style="width:40px; text-align:center;">
              <input type="checkbox" :checked="isAllChecked" @change="e => toggleCheckAll(e.target.checked)" />
            </th>
            <th>编码</th>
            <th>名称</th>
            <th>类别/品牌</th>
            <th>规格/单位</th>
            <th>售价/成本</th>
            <th>条码</th>
            <th>状态</th>
            <th style="width:200px;">操作</th>
          </tr>
        </thead>
        <tbody>
          <tr v-for="row in pageList" :key="row.id">
            <td style="text-align:center;">
              <input type="checkbox" :checked="selectedIds.has(row.id)" @change="e => toggleRowChecked(row.id, e.target.checked)" />
            </td>
            <td>{{ row.code }}</td>
            <td>{{ row.name }}</td>
            <td>{{ row.category }} / {{ row.brand || '-' }}</td>
            <td>{{ row.specification || '-' }} / {{ row.unit }}</td>
            <td>¥{{ Number(row.salePrice).toFixed(2) }} / ¥{{ Number(row.costPrice).toFixed(2) }}</td>
            <td>{{ row.barcode || '-' }}</td>
            <td>
              <span :class="['status', row.status]">{{ row.status === 'on' ? '上架' : '下架' }}</span>
            </td>
            <td>
              <button class="link" @click="openEdit(row)">编辑</button>
              <button class="link" @click="toggleStatus(row)">{{ row.status === 'on' ? '下架' : '上架' }}</button>
              <button class="link danger" @click="removeRow(row)">删除</button>
            </td>
          </tr>
          <tr v-if="pageList.length === 0">
            <td colspan="9" class="empty">暂无数据</td>
          </tr>
        </tbody>
      </table>
    </div>

    <div class="pagination" v-if="total > 0">
      <div class="left">共 {{ total }} 条</div>
      <div class="right">
        <button :disabled="currentPage===1" @click="currentPage = Math.max(1, currentPage-1)">上一页</button>
        <span>{{ currentPage }} / {{ totalPages }}</span>
        <button :disabled="currentPage===totalPages" @click="currentPage = Math.min(totalPages, currentPage+1)">下一页</button>
        <select v-model.number="pageSize">
          <option :value="10">10/页</option>
          <option :value="20">20/页</option>
          <option :value="50">50/页</option>
        </select>
      </div>
    </div>

    <!-- 弹窗 -->
    <div v-if="visible" class="dialog-mask" @click.self="visible=false">
      <div class="dialog">
        <div class="dialog-header">
          <div class="dialog-title">{{ isEdit ? '编辑商品' : '新增商品' }}</div>
          <button class="iconbtn" @click="visible=false">✕</button>
        </div>
        <div class="dialog-body">
          <div class="form-grid">
            <label>编码</label>
            <input v-model="form.code" placeholder="必填" />

            <label>名称</label>
            <input v-model="form.name" placeholder="必填" />

            <label>类别</label>
            <select v-model="form.category">
              <option value=""></option>
              <option v-for="c in productStore.categories" :key="c" :value="c">{{ c }}</option>
            </select>

            <label>品牌</label>
            <select v-model="form.brand">
              <option value=""></option>
              <option v-for="b in productStore.brands" :key="b" :value="b">{{ b }}</option>
            </select>

            <label>规格</label>
            <input v-model="form.specification" placeholder="如 330ml" />

            <label>单位</label>
            <input v-model="form.unit" placeholder="如 件/瓶/袋" />

            <label>售价</label>
            <input v-model.number="form.salePrice" type="number" step="0.01" />

            <label>成本</label>
            <input v-model.number="form.costPrice" type="number" step="0.01" />

            <label>状态</label>
            <select v-model="form.status">
              <option value="on">上架</option>
              <option value="off">下架</option>
            </select>

            <label>条码</label>
            <input v-model="form.barcode" />
          </div>
        </div>
        <div class="dialog-footer">
          <button class="ghost" @click="visible=false">取消</button>
          <button class="primary" @click="submitForm">确定</button>
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped>
.product-page {
  display: flex;
  flex-direction: column;
  height: 100vh;
  padding: 16px;
  background: #f6f8fa;
}
.header { display:flex; align-items:center; justify-content: space-between; margin-bottom: 12px; }
.title { font-size: 20px; font-weight: 600; }
.actions button { margin-left: 8px; }

.stats { display: grid; grid-template-columns: repeat(3, 1fr); gap: 12px; margin-bottom: 12px; }
.card { background: #fff; border-radius: 8px; padding: 12px; box-shadow: 0 1px 2px rgba(0,0,0,0.05); }
.card .num { font-size: 18px; font-weight: 700; }
.card .label { color: #666; font-size: 12px; margin-top: 6px; }
.card.on { border-left: 4px solid #52c41a; }
.card.off { border-left: 4px solid #ff4d4f; }

.filters { display:flex; align-items:center; gap: 8px; margin-bottom: 12px; }
.input, .select, .filters .select { height: 32px; padding: 0 8px; border: 1px solid #dcdfe6; border-radius: 6px; background: #fff; }
.ghost { background:#fff; border:1px solid #dcdfe6; border-radius:6px; height:32px; padding:0 12px; }
.primary { background:#1677ff; color:#fff; border: none; border-radius:6px; height:32px; padding:0 12px; }
button { cursor: pointer; }
button:disabled { opacity: 0.5; cursor: not-allowed; }

.table-wrap { flex: 1; overflow: auto; background: #fff; border-radius: 8px; }
.table { width: 100%; border-collapse: collapse; font-size: 14px; }
.table th, .table td { padding: 10px 12px; border-bottom: 1px solid #f0f0f0; text-align: left; }
.table thead th { position: sticky; top: 0; background: #fafafa; z-index: 1; }
.empty { text-align: center; color: #888; padding: 24px 0; }
.link { background: transparent; border: none; color: #1677ff; padding: 0 8px; }
.link.danger { color: #ff4d4f; }
.status { display: inline-block; padding: 2px 8px; border-radius: 999px; font-size: 12px; }
.status.on { background: #e6fffb; color: #13c2c2; }
.status.off { background: #fff1f0; color: #ff4d4f; }

.pagination { display:flex; justify-content: space-between; align-items: center; padding: 10px 0; }
.pagination .right { display:flex; align-items: center; gap: 8px; }

/* 弹窗 */
.dialog-mask { position: fixed; inset: 0; background: rgba(0,0,0,0.35); display:flex; align-items:center; justify-content:center; }
.dialog { width: 720px; max-width: 92vw; background: #fff; border-radius: 10px; overflow: hidden; box-shadow: 0 10px 30px rgba(0,0,0,0.2); }
.dialog-header { display:flex; align-items:center; justify-content: space-between; padding: 12px 16px; border-bottom: 1px solid #f0f0f0; }
.dialog-title { font-weight: 600; }
.iconbtn { background: transparent; border: none; font-size: 18px; cursor: pointer; }
.dialog-body { padding: 16px; max-height: 60vh; overflow: auto; }
.dialog-footer { padding: 12px 16px; border-top: 1px solid #f0f0f0; text-align: right; }

.form-grid { display: grid; grid-template-columns: 120px 1fr; gap: 10px 12px; align-items: center; }
.form-grid input, .form-grid select { height: 32px; padding: 0 8px; border: 1px solid #dcdfe6; border-radius: 6px; }
</style>


